/**
 * 内存缓存服务
 */

export class MemItem {
    val: any;
    last_time: number;
}

export class Mem<T> {

    static mapBuffer = new Map<string,MemItem>();

    /**
     * 移除超3天未使用的内存
     */
    static removeOldMem() {
        let time = Date.now() - 1000 * 3600 * 24 * 3
        for (var m of Mem.mapBuffer) {
            var k = m[0];
            var v = m[1];
            if (v.last_time < time) {
                Mem.mapBuffer.delete(k);
            }
        }

    }

    async get(key: string): Promise<T|undefined> {
        let item = Mem.mapBuffer.get(key + "")
        if (!item) {
            return;
        }
        item.last_time = Date.now();
        return item.val as T;
    }

    async set(key: string, val: T) {
        Mem.mapBuffer.set(key + "", {val: val, last_time: Date.now()});
    }

    async delete(key: string) {
        Mem.mapBuffer.delete(key + "")
    }


    async size() {
        return Mem.mapBuffer.size;
    }
}
